package com.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
	
	@GetMapping("/upload")
	public String upload() {
		return "upload";
	}
	
	
	@PostMapping("/upload")
	public Object uploadFile(MultipartFile file) {
		try {
			InputStream is = file.getInputStream();
			String filename = file.getOriginalFilename();
			String path = "D:/file_upload";
			File dir = new File(path);
			if(dir.exists()) {
				path = path+File.separator+filename;
			}else {
				dir.mkdir();
				path = path+File.separator+filename;
			}
			
			FileOutputStream fos = new FileOutputStream(new File(path));
			int len = 0;
			byte[] b = new byte[1024];
			
			while((len = is.read(b))>0) {
				fos.write(b,0,len);
			}
			fos.flush();
			is.close();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "upload";
	}

}
